import { Injectable, CanActivate, ExecutionContext, ForbiddenException, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../../database/prisma.service';

/**
 * 任务所有者守卫
 * 零隐患MFIS规范 - 解决隐患：#14 权限验证，#9 数据库查询安全
 */
@Injectable()
export class TaskOwnerGuard implements CanActivate {
  constructor(private readonly prisma: PrismaService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const taskId = parseInt(request.params.id);
    const user = request.user;

    if (!user || !user.doctor_id) {
      throw new ForbiddenException('用户认证信息无效');
    }

    if (isNaN(taskId) || taskId <= 0) {
      throw new ForbiddenException('无效的任务ID');
    }

    try {
      // 查询任务是否存在且属于当前用户
      const task = await this.prisma.scoringTask.findFirst({
        where: {
          task_id: taskId,
          doctor_id: user.doctor_id,
          deleted_at: null,
        },
        select: {
          task_id: true,
          doctor_id: true,
          status: true,
        },
      });

      if (!task) {
        throw new NotFoundException('任务不存在或无权访问');
      }

      // 将任务信息附加到请求中，供后续使用
      request.task = task;

      return true;

    } catch (error) {
      if (error instanceof NotFoundException) {
        throw error;
      }

      // 数据库查询错误不应该暴露详细信息
      throw new ForbiddenException('权限验证失败');
    }
  }
}